import sys
import os.path
from win32file import FindFilesW, error

def warning(msg):
    line = u'Warning: %s\n' % msg
    sys.stderr.write(line.encode(sys.stderr.encoding, 'replace'))

    
def relpath(path, start):
    try: return os.path.relpath(path, start)
    except ValueError: return path


def _truename(fn):
    try: return FindFilesW(fn, None)[0][8]
    except error: return fn.lower()


def canonical(path, base=".", _known = {}):
    key1 = path.lower()
    if key1 in _known:
        return _known[key1]
    path = os.path.normpath(os.path.join(base, path))
    key2 = path.lower()
    if key2 in _known:
        return _known[key2]
    components = path.split('\\')
    dir = components[0].upper()
    components = components[1:]
    for component in components:
        fn = dir + '\\' + component
        key = fn.lower()
        if key in _known:
            fn = _known[key]
        else:
            fn = _known[key] = dir + '\\' + _truename(fn)
        dir = fn    
    _known[key1] = _known[key2] = fn
    return fn

